package com.zkkj.demo.interceptor;

import com.zkkj.demo.annotation.FilterToken;
import com.zkkj.demo.dao.RedisDao;
import com.zkkj.demo.exception.UnauthorizedException;
import com.zkkj.demo.utils.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * author : cyc
 * Date : 2019/11/25
 * 所有请求统一的token鉴权拦截器
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisDao redisDao;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (dealFilterToken(handler))
            return true;
        String token = redisDao.getValue(TokenUtils.getToken());
        if (StringUtils.isNotBlank(token)) {
            return true;
        }
        throw new UnauthorizedException();
    }

    private boolean dealFilterToken(Object handler) {
        /**
         * isAssignableFrom 该方法意思就是判断当前对象是否可以被目标对象强转
         * 1.A是B的超类或者接口
         * 2.A和B是同一接口或者对象
         */
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.getMethodAnnotation(FilterToken.class) != null) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
